package com.example.sandbox.util;

import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class VerifySignUtil {

    public String verifySign(JSONObject params, String apiSecret) {
        StringBuilder sb = new StringBuilder();
        List<String> keyList = new ArrayList<>(params.keySet());
        Collections.sort(keyList);
        for (String key : keyList) {
            Object paramValue = params.get(key);
            if (!"signature".equals(key) && paramValue != null) {
                sb.append(key).append("=").append(paramValue).append("&");
            }
        }
        // 除了"sign"其他的拼接到一起签名
        String strToSign = sb.substring(0, sb.length() - 1);
        log.info("待签名字符串：{}", strToSign);
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA512, apiSecret.getBytes());
        String sign = Base64.getEncoder().encodeToString(hMac.digest(strToSign));
        log.info("获取到的签名：{}", sign);
        return sign;
    }
}
